package com.neusoft.databus.agent.parser;

import java.util.Map;

import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.databus.agent.parser.modbus.ModBusASCIIParser;
import com.neusoft.databus.agent.parser.modbus.ModBusRTUParser;
import com.neusoft.databus.agent.parser.modbus.ModBusTCPParser;
import com.neusoft.databus.common.bean.CommandBean;
import com.neusoft.databus.common.constant.DatabusConstant;
import com.neusoft.databus.common.enums.Protocol;
import com.neusoft.databus.common.exception.ConfigErrorException;
import com.neusoft.databus.common.parser.Parser;

/**
 * the parser factory <br>
 *
 * @author sunchf
 * @date 2019年1月7日 下午3:43:02
 */
public class ParserFactory {
    /**
     * 根据采集指令（指标组协议配置）创建对应的解析器.
     *
     * @param commandBean 采集指令
     * @return 解析器实例
     */
    @SuppressWarnings("unchecked")
    public static Parser createParser(final CommandBean commandBean) {
        Parser parser = null;
        final Protocol protocol = commandBean.getProtocol();
        switch (protocol) {
        case MODBUS_RTU:
            parser = new ModBusRTUParser();
            break;
        case MODBUS_TCP:
            parser = new ModBusTCPParser();
            break;
        case MODBUS_ASCII:
            parser = new ModBusASCIIParser();
            break;
        case OPC:
            parser = new OpcParser();
            break;
        case SNMP:
            parser = new SnmpParser();
            break;
        case PLUGIN:
            final String config = commandBean.getProtocolConfig();
            Map<String, Object> configMap = null;
            try {
                configMap = JsonUtils.jsonToMap(config);
            } catch (final Exception e) {
                throw new ConfigErrorException("协议配置解析错误, %s", config);
            }
            if ((null == configMap) || !configMap.containsKey("protocolName")) {
                throw new ConfigErrorException("协议配置未指定protocolName");
            }
            final String parserName = (String) configMap.get("protocolName");
            final StringBuilder sb = new StringBuilder();
            sb.append(DatabusConstant.PACKAGE_PREFIX_PARSER_CLASS).append(parserName.substring(0, 1).toUpperCase())
                    .append(parserName.substring(1, parserName.length()).toLowerCase()).append("Parser");
            try {
                final Class<Parser> clazz = (Class<Parser>) Class.forName(sb.toString());
                parser = clazz.newInstance();
            } catch (final ClassNotFoundException e) {
                throw new ConfigErrorException("使用自定义的数据采集，但系统未找到指定的类%s", sb.toString());
            } catch (final Exception e) {
                throw new ConfigErrorException("使用自定义的数据采集，实例化插件出错", e);
            }
            break;
        default:
            throw new ConfigErrorException("不支持的数据采集协议");
        }
        return parser;
    }
}
